package com.gamex.findit.controller.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gamex.findit.ResultCode;
import com.gamex.findit.internal.DefaultConfig;
import com.gamex.findit.model.ItemPurchaseHist;
import com.gamex.findit.model.Member;
import com.gamex.findit.model.MemberItem;
import com.gamex.findit.service.GameItemService;
import com.gamex.findit.service.ItemPurchaseHistService;
import com.gamex.findit.service.MemberItemService;
import com.gamex.findit.service.MemberService;
import com.gamex.findit.service.NoticeService;
import com.gamex.findit.util.CommonUtil;
import com.mysql.jdbc.StringUtils;

@Controller("memberItem")
public class MemberItemController {
	
	private static final Logger logger = LoggerFactory.getLogger(MemberItemController.class);
	
	@Autowired NoticeService noticeService;
	@Autowired GameItemService gameItemService;
	@Autowired MemberItemService memberItemService;
	@Autowired MemberService memberService;
	@Autowired DefaultConfig config;
	@Autowired ItemPurchaseHistService itemPurchaseHistService;
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/myItemList.*")
	public ResponseEntity<String> myItemList( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @RequestParam(value="userId",required=false) String userId) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
		ModelMap body = new ModelMap();
		MemberItem item = new MemberItem();
		item.setUserId(userId);
		
		if(StringUtils.isNullOrEmpty(userId)){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			
		}else{
			
			List<MemberItem> items = memberItemService.getMemberItem(item);
			if(items != null){
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
				body.addAttribute("list", items);
			}else{
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param item
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/spendMyItem.*")
	public ResponseEntity<String> spendMyItem( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @ModelAttribute MemberItem item) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
		ModelMap body = new ModelMap();
		MemberItem memberItem= null;
		int reqItemQuantity = item.getQuantity();
		if(StringUtils.isNullOrEmpty(item.getUserId()) || reqItemQuantity == 0  || item.getItemNo() == 0) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			
		}else{
			try {
				
				// 회원 보유 아이템 정보 추출
				memberItem = memberItemService.checkMemberItem(item.getItemNo(), item.getUserId());
				
				int minus = (memberItem.getQuantity() - reqItemQuantity);
				if(minus < 0) minus = 0;
				item.setQuantity(minus);
				memberItemService.updateMemberItem(item);
				
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param item
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/buyItem.*")
	public ResponseEntity<String> buyItem( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @ModelAttribute MemberItem item ) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        MemberItem memberItem= null;
		ModelMap body = new ModelMap();
		int reqItemQuantity = item.getQuantity();
		
		if(StringUtils.isNullOrEmpty(item.getUserId()) || item.getItemNo() == 0 || reqItemQuantity == 0) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			try {
				
				memberItem = memberItemService.checkMemberItem(item.getItemNo(), item.getUserId());
				
				if(memberItem == null){
					// 해당 회원이 요청 item 이 없으면 신규 등록
					memberItemService.insertMemberItem(item);
				}else{
					// 해당 회원이 요청 아이템이 있으면 quantity 추가
					item.setQuantity((memberItem.getQuantity() + reqItemQuantity));
					memberItemService.updateMemberItem(item);
				}
				
				// 아이템 구매이력
				addPurchaseHist(item.getUserId(), item.getItemNo(), reqItemQuantity);
				
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param item
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/buyItemAndSpendCoin.*")
	public ResponseEntity<String> buyItemAndSpendCoin( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @ModelAttribute MemberItem item
							, @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        MemberItem memberItem= null;
		ModelMap body = new ModelMap();
		int reqItemQuantity = item.getQuantity();
		
		if(StringUtils.isNullOrEmpty(item.getUserId()) || item.getItemNo() == 0 || reqItemQuantity == 0) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			
			try {
				
				memberItem = memberItemService.checkMemberItem(item.getItemNo(), member.getUserId());
				if(memberItem == null){
					// 해당 회원이 요청 item 이 없으면 신규 등록
					memberItemService.insertMemberItem(item);
				}else{
					// 해당 회원이 요청 아이템이 있으면 quantity 추가
					item.setQuantity((memberItem.getQuantity() + reqItemQuantity));
					memberItemService.updateMemberItem(item);
				}
				
				// 구매한 아이템 만큼 코인 절감
				member.setOperation("-");
				member.setCoin(member.getCoin() * reqItemQuantity);
				memberService.updateMemberNumeric(member);
			
				// 아이템 구매이력
				addPurchaseHist(member.getUserId(), item.getItemNo(), reqItemQuantity);
				
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	
	}
	
	/**
	 * @param userId
	 * @param itemNo
	 * @param quantity
	 */
	@Async
	private void addPurchaseHist(String userId, int itemNo, int quantity){
		ItemPurchaseHist hist = new ItemPurchaseHist();
		
		hist.setUserId(userId);
		hist.setItemNo(itemNo);
		hist.setQuantity(quantity);
		try {
			itemPurchaseHistService.insertItemPurchaseHist(hist);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
